
import { useAppData, useLocation } from '@umijs/max';
import { useMemo } from 'react';
import cloneDeep from 'lodash/cloneDeep';
const handleMenu = (item) => {
    return {
        key: item?.path,
        label: <span>{item?.name}</span>,
        children: item?.children,
    };
};
const handleRoute = (arr) => {
    return arr?.reduce?.((result, item) => {
        item?.routes?.forEach?.((items) => {
            if (items?.routes) {
                items.children = handleRoute([items]);
            }
            result.push(handleMenu(items));
        });
        return result;
    }, []);
};

/**
 * 
 * @returns {
 *   routs    当前主菜单的子路由
 *   openKey  当前路由的key
 *   nowRoute 当前路由节点信息
 * }
 */
export default function useMenuData() {
    const { clientRoutes = [], routes: router } = useAppData();
    const { pathname } = useLocation();

    const routes = useMemo(() => {
        const route = cloneDeep(clientRoutes);
        return handleRoute(route); //根据路由生成菜单
    }, [clientRoutes]);
    const { openKey, nowRoute } = useMemo(() => {
        const routesArr = Object.values(router);
        const nowRoute = routesArr?.find?.((item) => item.path === pathname); //当前路由信息
        const parentRoute = routesArr?.find?.(
            (item) => nowRoute.parentId === item.id,
        ); //当前路由的父路由
        return {
            openKey: parentRoute?.path,
            nowRoute,
        };
    }, [pathname, router]);
    return {
        routes,
        openKey,
        nowRoute,
    }
}